import Taro, {
  showLoading,
  hideLoading,
  showToast,
  request as TaroRequest,
} from "@tarojs/taro";
import i18next from "i18next";
import { useUserStore } from "@/stores/user";
import { useLanguageStore } from "@/stores/language";
// 基础配置
declare const BASE_URL: string;
const DEFAULT_HEADER = {
  "Content-Type": "application/json",
};

// 获取token的方法
const getToken = () => {
  return useUserStore.getState().token;
};

// 请求封装
export const request = async <T = any>(
  options: RequestConfig
): Promise<RequestResponse<T>> => {
  const { url, method = "GET", data, header, isShowLoading = true } = options;
  const currentLanguage = useLanguageStore.getState().currentLanguage;
  if (isShowLoading) {
    showLoading({
      title: i18next.t("common.loading"),
      mask: true,
    });
  }

  try {
    const token = getToken();
    const headers = {
      ...DEFAULT_HEADER,
      ...header,
      ...(token && { Authorization: `Bearer ${token}` }),
      "Accept-Language": currentLanguage, // 添加语言请求头
    };

    const response = await TaroRequest({
      url: `${BASE_URL}${url}`,
      method,
      data,
      header: headers,
    });

    if (isShowLoading) {
      hideLoading();
    }

    if (response.statusCode === 200) {
      const responseData = response.data as RequestResponse<T>;

      if (responseData.code === 200) {
        return responseData;
      } else if (responseData.code === 401) {
        useUserStore.getState().logout();
        Taro.navigateTo({ url: "/pages/login/index" });
        throw new Error("登录已过期，请重新登录");
      } else {
        throw new Error(responseData.msg || "请求失败");
      }
    } else {
      throw new Error(`请求失败，状态码: ${response.statusCode}`);
    }
  } catch (error) {
    if (isShowLoading) {
      hideLoading();
    }
    console.log(error.message);
    showToast({
      title: error.message || i18next.t("common.networkError"),
      icon: "none",
      duration: 2000,
    });
    throw error;
  }
};
